﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Projects.Dom;
using MonoDevelop.Projects.Dom.Parser;

using Microsoft.FSharp.Text.Lexing;

using Coq.MonoDevelop;
using MonoDevelop.Core;


namespace Coq.MonoDevelop
{
    class CoqTextEditorCompletion : CompletionTextEditorExtension
    {
        public CoqTextEditorCompletion()
        {
        }

        public override bool ExtendsEditor(Document doc, IEditableTextBuffer editor)
        {
            return Common.SupportedExtension(System.IO.Path.GetExtension(doc.FileName.ToString()));
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public override bool KeyPress(Gdk.Key key, char keyChar, Gdk.ModifierType modifier)
        {
            return base.KeyPress(key, keyChar, modifier);
        }

        public override IParameterDataProvider HandleParameterCompletion(CodeCompletionContext completionContext, char completionChar)
        {
            //return base.HandleParameterCompletion(completionContext, completionChar);
            return null;
        }

        public override ICompletionDataList HandleCodeCompletion(CodeCompletionContext completionContext, char completionChar, ref int triggerWordLength)
        {
            if (completionChar == '.')
                return CodeCompletionCommand(completionContext);
            
            return null;
            //return base.HandleCodeCompletion(completionContext, completionChar, ref triggerWordLength);
        }

        public override ICompletionDataList CodeCompletionCommand(CodeCompletionContext completionContext)
        {
            var config = IdeApp.Workspace.ActiveConfiguration;
            
            //retrieve document
            var doc = (CoqParsedDocument)this.Document.ParsedDocument;

            //Create scopes from AST
            if (doc.Ast == null)
                return new CompletionDataList();
            
            var r = Scope.CoqASTWalker(doc.Ast);

            //ContextInfo
            int line = completionContext.TriggerLine;
            int column = completionContext.TriggerLineOffset;

            Position p = new Position("", line, 0, column);

            //search for correct line
            IEnumerable<CompletionData> retlist = null;

            retlist = from l in Scope.GetScopeStateIdentifiers(p, r)
                      select new CompletionData(l.Item1, new IconId("md-id"));

            return new CompletionDataList(retlist);

            //return null;
        }
    }
}
